package core

import (
	"fmt"
	"sync"
)

/*
   玩家管理模块
*/

type PlayerManager struct {
	Players 	map[uint32]*Player	//管理的玩家信息
	playerLock    sync.RWMutex        //读写玩家的读写锁
}

//提供一个对外的世界管理模块句柄
var PlayerMgrObj *PlayerManager

/*
   创建一个玩家管理模块
*/
func init(){
	PlayerMgrObj = &PlayerManager{
		Players: make(map[uint32] *Player),
	}
}


//添加玩家
func (playMgr *PlayerManager) Add(player *Player) {
	//保护共享资源Map 加写锁
	playMgr.playerLock.Lock()
	defer playMgr.playerLock.Unlock()

	//将玩家添加到PlayerManager中
	playMgr.Players[player.Pid] = player

	fmt.Println("player add to PlayerManager successfully: player num = ", playMgr.Len())
}
//删除玩家
func (playMgr *PlayerManager) RemovePlayerByPid(pid uint32){
	//保护共享资源Map 加写锁
	playMgr.playerLock.Lock()
	defer playMgr.playerLock.Unlock()

	//将玩家添加到PlayerManager中
	delete(playMgr.Players, pid)

	fmt.Println("player Remove playerID=",pid, " successfully: player num = ", playMgr.Len())
}

func (playMgr *PlayerManager) GetPlayerByPid(pid uint32) *Player{
	//保护共享资源Map 加写锁
	playMgr.playerLock.Lock()
	defer playMgr.playerLock.Unlock()

	return playMgr.Players[pid]
}

//获取所有玩家的信息
func (playMgr *PlayerManager) GetAllPlayers() []*Player {
	playMgr.playerLock.RLock()
	defer playMgr.playerLock.RUnlock()

	//创建返回的player集合切片
	Players := make([]*Player, 0)

	//添加切片
	for _, v := range playMgr.Players {
		Players = append(Players, v)
	}

	//返回
	return Players
}

//获取玩家池玩家数量
func (playMgr *PlayerManager) Len() int{
	return len(playMgr.Players)
}

func (playMgr *PlayerManager) ClearPlayer() {
	//保护共享资源Map 加写锁
	playMgr.playerLock.Lock()
	defer playMgr.playerLock.Unlock()

	//停止并删除全部的玩家信息
	for playerID, player := range playMgr.Players{
		//清空玩家信息，踢掉在线的玩家
		player.Conn.Stop()
		//删除
		delete(playMgr.Players, playerID)
	}

}



